#!/usr/bin/env python3
"""
VideoGrabber 启动脚本
提供便捷的启动方式和环境检查
"""

import sys
import os
import subprocess
from pathlib import Path


def check_python_version():
    """检查Python版本"""
    if sys.version_info < (3, 8):
        print("❌ 错误: 需要Python 3.8或更高版本")
        print(f"当前版本: {sys.version}")
        return False
    print(f"✅ Python版本检查通过: {sys.version.split()[0]}")
    return True


def check_dependencies():
    """检查依赖是否安装"""
    required_packages = [
        'PyQt6',
        'requests', 
        'validators'
    ]
    
    missing_packages = []
    
    for package in required_packages:
        try:
            __import__(package.lower().replace('-', '_'))
            print(f"✅ {package} 已安装")
        except ImportError:
            missing_packages.append(package)
            print(f"❌ {package} 未安装")
    
    if missing_packages:
        print(f"\n缺少依赖包: {', '.join(missing_packages)}")
        print("请运行以下命令安装依赖:")
        print("pip install -r requirement.txt")
        return False
    
    return True


def check_files():
    """检查必要文件是否存在"""
    required_files = [
        'main.py',
        'config.py',
        'logger.py',
        'utils.py',
        'downloader.py',
        'requirement.txt',
        'styles/main.qss'
    ]
    
    missing_files = []
    base_path = Path(__file__).parent
    
    for file_path in required_files:
        full_path = base_path / file_path
        if full_path.exists():
            print(f"✅ {file_path} 存在")
        else:
            missing_files.append(file_path)
            print(f"❌ {file_path} 不存在")
    
    if missing_files:
        print(f"\n缺少文件: {', '.join(missing_files)}")
        return False
    
    return True


def main():
    """主函数"""
    print("VideoGrabber 启动检查")
    print("=" * 50)
    
    # 检查Python版本
    if not check_python_version():
        sys.exit(1)
    
    print("\n检查依赖包...")
    # 检查依赖
    if not check_dependencies():
        sys.exit(1)
    
    print("\n检查项目文件...")
    # 检查文件
    if not check_files():
        sys.exit(1)
    
    print("\n" + "=" * 50)
    print("✅ 所有检查通过，启动VideoGrabber...")
    print("=" * 50)
    
    # 启动主程序
    try:
        # 切换到脚本目录
        os.chdir(Path(__file__).parent)
        
        # 启动主程序
        subprocess.run([sys.executable, 'main.py'], check=True)
        
    except subprocess.CalledProcessError as e:
        print(f"❌ 启动失败: {e}")
        sys.exit(1)
    except KeyboardInterrupt:
        print("\n⏹️  用户中断")
        sys.exit(0)
    except Exception as e:
        print(f"❌ 意外错误: {e}")
        sys.exit(1)


if __name__ == "__main__":
    main()